package com.hong.zoo;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class ZkDistributeLock implements Lock{

    private String lockPath;

    private ZkClient client;

    public ZkDistributeLock(String lockPath) {
        this.lockPath = lockPath;
        client = new ZkClient("localhost:2181");
        client.setZkSerializer(new MyZkSerializer());
    }

    /**
     * 如果获取不到锁,则阻塞等待
     */
    @Override
    public void lock() {
        if (!tryLock()){
            // 没获得锁,阻塞自己
            waitForLock();
            lock();
        }
    }

    /**
     *  注册节点的watcher,阻塞等待
     */
    private void waitForLock() {
        CountDownLatch cdl = new CountDownLatch(1);
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataChange(String lockPath, Object data) throws Exception {

            }

            @Override
            public void handleDataDeleted(String lockPath) throws Exception {
                System.out.println("===收到节点被删除了===");
                cdl.countDown();
            }
        };

        client.subscribeDataChanges(lockPath,listener);

        // 阻塞自己
        if (this.client.exists(lockPath)){
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 取消注册
        client.unsubscribeDataChanges(lockPath,listener);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    /**
     * 非阻塞获取锁
     * @return
     */
    @Override
    public boolean tryLock() {
        try {
            client.createEphemeral(lockPath);
        } catch (ZkNodeExistsException e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        client.delete(lockPath);
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
